<template>
    <div :class="['draggable-navbar', props.isActive === true ? 'isActive' : '']" :style="{
        userSelect: isDragging ? 'none' : 'auto',
        cursor: 'move',
        transform: `translate(${props.x}px,${props.y}px)`
    }" @mousedown="onMouseDown">
        <slot></slot>
    </div>
</template>
  
<script setup lang="ts">
//申明坐标修改事件
const $emit = defineEmits(['startMove', 'onMoving', 'endMove']);
const props = defineProps({
    index: {
        type: Number,
        default: 0
    },
    x: {
        type: Number,
        default: 0
    },
    y: {
        type: Number,
        default: 0
    },
    axis: {
        type: String,
        default: 'both'
    },
    isActive:{
        type: Boolean,
        default: false
    },
    isDraggable:{
        type: Boolean,
        default: true
    },
});
const isDragging = ref(false);
const MouseStartPosition = reactive({ x: 0, y: 0 });
const currentPosition = reactive({ x: props.x, y: props.y });

function onMouseDown(event: any) {
    if(props.isDraggable){
        isDragging.value = true;
        MouseStartPosition.x = event.clientX;
        MouseStartPosition.y = event.clientY;
        $emit('startMove', props.index, MouseStartPosition);
        // console.log(props.index, MouseStartPosition);
        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    }
};

function onMouseUp() {
    $emit('endMove', props.index);
    isDragging.value = false;
    window.removeEventListener('mousemove', onMouseMove);
    window.removeEventListener('mouseup', onMouseUp);
    // console.log('拖拽结束')
};

function onMouseMove(event: any) {    
    if (isDragging.value) {
        if (props.axis === "x" || props.axis === "both") {
            currentPosition.x = event.clientX;
        }
        if (props.axis === "y" || props.axis === "both") {
            currentPosition.y = event.clientY;
        }
        $emit('onMoving', props.index, currentPosition);
    }
};

</script>
<style  scoped lang="scss">
.draggable-navbar {
    z-index: 1;
    position: relative;
    /* 添加您的样式 */
    // transition: transform 0.1s;
}
.draggable-navbar:hover{
    z-index: 2;
}
.isActive{
    z-index: 3;
}
</style>